<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/7/12
 * Time: 19:06
 */

namespace app\home\controller;


class Cart extends Common
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $this->templateTitle("购物车");
        //获取购物车列表
        $list = \app\common\model\Cart::carList(session("user_id"));
        $this->assign("list", $list);
        $is_login = session("user_id")?1:0;
        $this->assign("is_login", $is_login);
        return $this->fetch("index");
    }

    /**
     * 加入购物车
     */
    public function addCart()
    {
        $good_id = input("good_id");
        $spec_id = input("spec_id");
        $user_id = session("user_id");
        $num = input("num")?:1;
        try{
            $res = \app\common\model\Cart::addCar($user_id, $good_id, $spec_id, $num);
            $cart_num = \app\common\model\Cart::getCartNums($user_id);
            $this->ajaxSuccess("加入购物车成功", $cart_num);
        }catch (\Exception $e){
            $this->ajaxError($e->getMessage());
        }
    }

    /**
     * 购物车加减
     */
    public function addDelete($type, $cart_id)
    {
        try{
            $res = \app\common\model\Cart::carAddDelete(session("user_id"), $type, $cart_id);
            $this->ajaxSuccess($res);
        }catch (\Exception $e){
            $this->ajaxError($e->getMessage());
        }
    }

    public function cartRemove()
    {
        try{
            $cart_id = explode(",", input("cart_id"));
            \app\common\model\Cart::carRemove(session("user_id"), $cart_id);
            $this->ajaxSuccess("删除成功");
        }catch (\Exception $e){
            $this->ajaxError($e->getMessage());
        }

    }


}